﻿Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Runtime.Serialization
Imports System.Xml.Serialization
Imports System.IO

Public Class AwayMessageCollection
    Inherits ObservableCollection(Of AwayMessage)
    Shared saveFolder As String, fn As String

    Shared Sub New()
        saveFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WhileAway")
        fn = Path.Combine(saveFolder, "Messages.dat")
    End Sub

    Public Function Save() As Boolean
        Directory.CreateDirectory(saveFolder)

        Try
            Dim ser As New XmlSerializer(GetType(AwayMessageCollection))
            Using str As New StreamWriter(fn)
                ser.Serialize(str, Me)
                str.Close()
            End Using
            Return True
        Catch
        End Try

        Return False
    End Function

    Public Sub LoadFromDisk()
        If Not File.Exists(fn) Then
            Return
        End If

        Try
            Dim ser As New XmlSerializer(GetType(AwayMessageCollection))
            Using str As New StreamReader(fn)
                Dim toLoad As AwayMessageCollection = DirectCast(ser.Deserialize(str), AwayMessageCollection)

                For Each msg As AwayMessage In toLoad
                    Me.Add(msg)
                Next
            End Using
        Catch
        End Try
    End Sub

End Class
